package org.asiainfo.im.server.runner;

import com.corundumstudio.socketio.SocketIOServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.asiainfo.im.server.handler.TestEventHandler;
import org.asiainfo.im.server.listener.SocketIOServerConnectListener;
import org.asiainfo.im.server.listener.SocketIOServerDisConnectListener;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * socket-io 服务端启动
 *
 * @author dotor-ww
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class SocketIOServerRunner implements CommandLineRunner, DisposableBean {

    private final SocketIOServer socketIOServer;

    private final TestEventHandler testEventHandler;

    /**
     * 启动
     *
     * @param args 参数
     */
    @Override
    public void run(String... args) {
        // 监听连接
        socketIOServer.addConnectListener(new SocketIOServerConnectListener());
        // 监听断开连接
        socketIOServer.addDisconnectListener(new SocketIOServerDisConnectListener());
        // 添加自定义事件
        socketIOServer.addListeners(testEventHandler);
        // 启动
        socketIOServer.start();
        System.out.println(
            """
                 _____          _____                         \s
                |_   _|        /  ___|                        \s
                  | | _ __ ___ \\ `--.  ___ _ ____   _____ _ __\s
                  | || '_ ` _ \\ `--. \\/ _ \\ '__\\ \\ / / _ \\ '__|
                 _| || | | | | /\\__/ /  __/ |   \\ V /  __/ |  \s
                 \\___/_| |_| |_\\____/ \\___|_|    \\_/ \\___|_|  \s
                                                              \s
                :: ImServer :: start success            (v1.0.0)""");
    }

    /**
     * 销毁
     */
    @Override
    public void destroy() {
        // 停止
        socketIOServer.stop();
    }
}
